package com.dhms.uikit

import android.Manifest
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.dhms.uikit.databinding.FragmentAudioRecordBottomSheetBinding
import com.dhms.uikit.media.MediaActivity
import com.dhms.uikit.media.MediaActivity.Companion.AUDIO_EXTENSION
import com.dhms.uikit.media.MediaActivity.Companion.BROADCAST_FILE_PATH_KEY
import com.dhms.uikit.media.MediaActivity.Companion.BROADCAST_FILE_TYPE_KEY
import com.dhms.uikit.media.MediaActivity.Companion.FILENAME_FORMAT
import com.dhms.uikit.media.MediaType

import java.io.File
import java.util.*

/**
 * A bottom sheet to record audio.
 *
 * @param viewId
 * @param isRecordMode Sets whether the view is in recording mode.
 */
class AudioRecordBottomSheet(
    private val viewId: String,
    private val isRecordMode: Boolean
) :
    TitleBottomSheet(),
    AudioRecordView.AudioRecordCallback {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
        }
    }

    private var _audioFileName: String? = null
    val audioFileName get() = _audioFileName

    private var _binding: FragmentAudioRecordBottomSheetBinding? = null

    // Requesting permission to RECORD_AUDIO
    private var permissionToRecordAccepted = false
    private var permissions: Array<String> = arrayOf(Manifest.permission.RECORD_AUDIO)

    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentAudioRecordBottomSheetBinding.inflate(inflater, container, false)
        this.activity?.let {
            ActivityCompat.requestPermissions(
                it,
                permissions,
                REQUEST_RECORD_AUDIO_PERMISSION
            )
        }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.lifecycleOwner = viewLifecycleOwner
        binding.isRecordMode = isRecordMode
        Log.d(TAG, "onViewCreated: $_audioFileName")
        binding.audioRecordView.audioRecordCallback = this
        _audioFileName = null
        if (context?.checkSelfPermission(permissions[0]) == PackageManager.PERMISSION_GRANTED) {
            if (isRecordMode) {
                setRecordListener()
            } else {
                startRecord()
            }
        }
    }

    private fun startRecord() {
        _audioFileName = File(
            context?.getExternalFilesDir(viewId)?.path + "/${
                Date().toFormatDate(
                    FILENAME_FORMAT
                )
            }" + AUDIO_EXTENSION
        ).path ?: return
        binding.audioRecordView.start(_audioFileName!!)
    }

    private fun setRecordListener() {
        binding.audioRecordView.apply {
            setOnClickListener {
                if (binding.isRecording) {
                    cancel()
                    binding.isRecording = false
                } else {
                    startRecord()
                    binding.isRecording = true
                }
            }
        }
        binding.dialogNegativeBtn.setOnClickListener {
            _audioFileName = null
            dismiss()
        }
        binding.dialogPositiveBtn.setOnClickListener {
            if (_audioFileName == null) {
                Toast.makeText(context, "未创建任何录音！", Toast.LENGTH_SHORT).show()
            }
            dismiss()
        }
    }

    override fun getTitle(): String {
        return resources.getString(R.string.audio_record_bottom_sheet_title)
    }


    companion object {
        const val REQUEST_RECORD_AUDIO_PERMISSION = 200
        const val TAG = "AudioRecordBottomSheet"

        @JvmStatic
        fun newInstance(viewId: String, isRecordMode: Boolean = false) =
            AudioRecordBottomSheet(viewId, isRecordMode).apply {
                arguments = Bundle().apply {
                }
            }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        permissionToRecordAccepted = if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
            grantResults[0] == PackageManager.PERMISSION_GRANTED
        } else {
            false
        }
        if (!permissionToRecordAccepted) {
            Toast.makeText(
                context,
                "You have no audio record permission",
                Toast.LENGTH_SHORT
            ).show()
        } else {
            _audioFileName?.let { binding.audioRecordView.start(_audioFileName!!) }
        }
    }

    override fun onStarted() {}

    override fun onCompleted(fileName: String, duration: Int) {
        if (duration < 1) {
            Toast.makeText(context, "录音时间至少1s！", Toast.LENGTH_SHORT).show()
            _audioFileName = null
        }
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        binding.audioRecordView.cancel()

        val intent =
            Intent(MediaActivity.BROADCAST_CREATE_ACTION + viewId)
        if (_audioFileName != null) {
            intent.putExtra(BROADCAST_FILE_PATH_KEY, Uri.fromFile(File(_audioFileName!!)))
            intent.putExtra(BROADCAST_FILE_TYPE_KEY, MediaType.AUDIO)
        }
        activity?.sendBroadcast(intent)
    }
}
